package com.xky.ui.module.productManagement.select;

import com.xky.pojo.Products;
import lombok.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

@Setter
public class SelectProduct extends JFrame {

    @Getter
    private static Integer Id;
    private final ProductService productService;
    private JTextField searchField;
    private JRadioButton idSearchRadio;
    private JRadioButton nameSearchRadio;
    private JTable resultTable;
    private DefaultTableModel tableModel;
    private JScrollPane scrollPane;
    private boolean showingResults = false;
    
    public SelectProduct(){
        setTitle("查询商品");
        setSize(600, 400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        productService = new ProductService();
        init();
        setVisible(true);
    }

    void init(){
        setLayout(new BorderLayout());

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        
        // 创建搜索面板
        JPanel searchPanel = createSearchPanel();
        mainPanel.add(searchPanel, BorderLayout.NORTH);
        
        // 创建结果表格
        createResultTable();
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        
        // 创建底部按钮面板
        JPanel buttonPanel = createButtonPanel();
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        add(mainPanel, BorderLayout.CENTER);
    }
    
    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(new EmptyBorder(0, 0, 10, 0));
        
        // 创建搜索类型选择面板
        JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        idSearchRadio = new JRadioButton("按ID查询");
        idSearchRadio.setSelected(true);
        nameSearchRadio = new JRadioButton("按名称/编码查询");
        
        ButtonGroup group = new ButtonGroup();
        group.add(idSearchRadio);
        group.add(nameSearchRadio);
        
        radioPanel.add(idSearchRadio);
        radioPanel.add(nameSearchRadio);
        
        panel.add(radioPanel, BorderLayout.NORTH);
        
        // 创建搜索框面板
        JPanel searchBoxPanel = new JPanel(new BorderLayout(5, 0));
        
        JLabel searchLabel = new JLabel("查询条件:");
        searchLabel.setFont(new Font("黑体", Font.BOLD, 14));
        searchBoxPanel.add(searchLabel, BorderLayout.WEST);
        
        searchField = new JTextField();
        searchField.setFont(new Font("宋体", Font.PLAIN, 14));
        searchBoxPanel.add(searchField, BorderLayout.CENTER);
        
        JButton searchButton = new JButton("搜索");
        searchButton.setBackground(Color.PINK);
        searchButton.addActionListener(e -> performSearch());
        searchBoxPanel.add(searchButton, BorderLayout.EAST);
        
        panel.add(searchBoxPanel, BorderLayout.CENTER);
        
        // 添加提示标签
        JLabel tipLabel = new JLabel("提示: 模糊查询支持部分商品名称或编码");
        tipLabel.setFont(new Font("宋体", Font.ITALIC, 12));
        tipLabel.setForeground(Color.GRAY);
        panel.add(tipLabel, BorderLayout.SOUTH);
        
        // 添加搜索框输入监听器，按回车时执行搜索
        searchField.addActionListener(e -> performSearch());
        
        // 添加搜索模式切换时的监听器
        ActionListener radioListener = e -> {
            if (idSearchRadio.isSelected()) {
                tipLabel.setText("提示: 请输入商品ID");
                searchField.getDocument().removeDocumentListener(documentListener);
            } else {
                tipLabel.setText("提示: 模糊查询支持部分商品名称或编码");
                searchField.getDocument().addDocumentListener(documentListener);
            }
        };
        
        idSearchRadio.addActionListener(radioListener);
        nameSearchRadio.addActionListener(radioListener);
        
        return panel;
    }
    
    private void createResultTable() {
        // 创建表格模型
        String[] columnNames = {"商品ID", "商品编码", "商品名称", "分类ID", "计量单位", "最小库存", "是否激活"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 设置表格不可编辑
            }
        };
        
        resultTable = new JTable(tableModel);
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultTable.setRowHeight(25);
        resultTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, 14));
        
        // 设置列宽
        resultTable.getColumnModel().getColumn(0).setPreferredWidth(100);  // 商品ID
        resultTable.getColumnModel().getColumn(1).setPreferredWidth(100); // 商品编码
        resultTable.getColumnModel().getColumn(2).setPreferredWidth(100); // 商品名称
        resultTable.getColumnModel().getColumn(3).setPreferredWidth(100);  // 分类ID
        resultTable.getColumnModel().getColumn(4).setPreferredWidth(100);  // 计量单位
        resultTable.getColumnModel().getColumn(5).setPreferredWidth(100);  // 最小库存
        resultTable.getColumnModel().getColumn(6).setPreferredWidth(100);  // 是否激活
        
        // 添加表格点击事件
        resultTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) { // 双击
                    int selectedRow = resultTable.getSelectedRow();
                    if (selectedRow >= 0) {
                        Id = (Integer) tableModel.getValueAt(selectedRow, 0);
                        JOptionPane.showMessageDialog(SelectProduct.this, 
                            "已选择ID为 " + Id + " 的商品: " + tableModel.getValueAt(selectedRow, 2),
                            "已选择", JOptionPane.INFORMATION_MESSAGE);
                        dispose();
                    }
                }
            }
        });
        
        scrollPane = new JScrollPane(resultTable);
        scrollPane.setPreferredSize(new Dimension(580, 250));
    }
    
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        
        JButton selectButton = new JButton("选择");
        selectButton.setFont(new Font("黑体", Font.BOLD, 14));
        selectButton.setBackground(Color.PINK);
        selectButton.setPreferredSize(new Dimension(100, 30));
        selectButton.addActionListener(e -> {
            int selectedRow = resultTable.getSelectedRow();
            if (selectedRow >= 0) {
                Id = (Integer) tableModel.getValueAt(selectedRow, 0);
                JOptionPane.showMessageDialog(SelectProduct.this, 
                    "已选择ID为 " + Id + " 的商品: " + tableModel.getValueAt(selectedRow, 2),
                    "已选择", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(SelectProduct.this, 
                    "请先选择一个商品", 
                    "提示", JOptionPane.WARNING_MESSAGE);
            }
        });
        
        JButton cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("黑体", Font.BOLD, 14));
        cancelButton.setBackground(Color.PINK);
        cancelButton.setPreferredSize(new Dimension(100, 30));
        cancelButton.addActionListener(e -> {
            Id = null;
            dispose();
        });
        
        panel.add(selectButton);
        panel.add(Box.createHorizontalStrut(20));
        panel.add(cancelButton);
        
        return panel;
    }
    
    // 文档监听器，用于实时搜索
    private DocumentListener documentListener = new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            if (nameSearchRadio.isSelected() && showingResults) {
                performSearch();
            }
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            if (nameSearchRadio.isSelected() && showingResults) {
                performSearch();
            }
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            if (nameSearchRadio.isSelected() && showingResults) {
                performSearch();
            }
        }
    };
    
    // 执行搜索
    private void performSearch() {
        String searchText = searchField.getText().trim();
        
        if (searchText.isEmpty()) {
            if (idSearchRadio.isSelected()) {
                JOptionPane.showMessageDialog(this, "请输入商品ID", "提示", JOptionPane.WARNING_MESSAGE);
            } else {
                // 如果是模糊查询且输入为空，显示所有商品
                displayAllProducts();
            }
            return;
        }
        
        if (idSearchRadio.isSelected()) {
            // ID查询
            try {
                Integer id = Integer.valueOf(searchText);
                if (id <= 0) {
                    JOptionPane.showMessageDialog(this, "商品ID必须为正整数", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                
                List<Products> productList = ProductService.selectProductById(id);
                updateTableWithResults(productList);
                
                if (productList.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "未查找到ID为 " + id + " 的商品", "查找结果", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            // 模糊查询
            List<Products> productList = ProductService.searchProductsByKeyword(searchText);
            updateTableWithResults(productList);
            
            if (productList.isEmpty() && !showingResults) {
                JOptionPane.showMessageDialog(this, "未找到匹配的商品", "查找结果", JOptionPane.INFORMATION_MESSAGE);
            }
        }
        
        showingResults = true;
    }
    
    // 显示所有商品
    private void displayAllProducts() {
        List<Products> productList = ProductService.selectAllProducts();
        updateTableWithResults(productList);
    }
    
    // 更新表格数据
    private void updateTableWithResults(List<Products> productList) {
        // 清空表格
        tableModel.setRowCount(0);
        
        // 添加结果到表格
        for (Products product : productList) {
            Object[] rowData = {
                product.getProductId(),
                product.getProductCode(),
                product.getProductName(),
                product.getCategoryId(),
                product.getUnitOfMeasure(),
                product.getMinStockLevel(),
                product.getIsActive()
            };
            tableModel.addRow(rowData);
        }
        
        // 刷新表格
        tableModel.fireTableDataChanged();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SelectProduct::new);
    }

}
